package com.example.yichuangyun.mvvm.di.retrofit;

import android.annotation.SuppressLint;
import android.util.Log;

import com.example.yichuangyun.application.MyApplication;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.model.EventBusModel;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * 全局统一使用的OkHttpClient工具，okhttp版本：okhttp3
 */
public class OkHttpHelper {
    private static final long DEFAULT_READ_TIMEOUT_MILLIS = 30 * 1000;
    private static final long DEFAULT_WRITE_TIMEOUT_MILLIS = 30 * 1000;
    private static final long DEFAULT_CONNECT_TIMEOUT_MILLIS = 30 * 1000;

    private static volatile OkHttpHelper sInstance;
    private final OkHttpClient mOkHttpClient;

    private OkHttpHelper() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(msg -> {
            String message = null;
            try {//需判断json是什么格式
                if (msg.startsWith("{")) {
                    JSONObject jsonObject = new JSONObject(msg);
                    //最重要的方法，就一行，返回格式化的json字符串，其中的数字4是缩进字符数
                    message = jsonObject.toString(4);
                } else if (msg.startsWith("[")) {
                    JSONArray jsonArray = new JSONArray(msg);
                    message = jsonArray.toString(4);
                } else {
                    message = msg;
                }
            } catch (JSONException e) {
                message = msg;
            }
            Log.e("okHttp---", message);
            if (message.contains("\"result\": 201")) {
                if (!Constant.isLogout) {
                    EventBus.getDefault().post(new EventBusModel(Constant.logout));
                    Constant.isLogout = true;
                }
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

//        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        //包含header、body数据
//        loggingInterceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        @SuppressLint({"CustomX509TrustManager", "TrustAllX509TrustManager"})
        X509TrustManager xtm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
        SSLContext sslContext;
        SSLSocketFactory sslSocketFactory = null;
        try {
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .writeTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .connectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .sslSocketFactory(sslSocketFactory, xtm)
                .hostnameVerifier((s, sslSession) -> true)
                // 失败重发
                .retryOnConnectionFailure(true)
                // 添加header
                .addInterceptor(chain -> {
                    Request request = chain.request();
                    Request builder = request.newBuilder()
                            .header("authorization", "TOKEN " + MyApplication.manager.getToken())
                            .header("channel", "1")
                            .build();
                    return chain.proceed(builder);
                })
                // 添加log拦截器
                .addInterceptor(loggingInterceptor)
                .build();
    }

    public static OkHttpHelper getInstance() {
        if (sInstance == null) {
            synchronized (OkHttpHelper.class) {
                if (sInstance == null) {
                    sInstance = new OkHttpHelper();
                }
            }
        }
        return sInstance;
    }

    public OkHttpClient getOkHttpClient() {
        return mOkHttpClient;
    }
}
